<template>
  <div class="order-detail">
    <el-page-header @back="goBack" :title="'订单详情'" />

    <el-card class="detail-card" v-loading="loading">
      <!-- 订单状态 -->
      <div class="status-bar">
        <el-steps :active="getStatusStep(orderInfo.status)" finish-status="success">
          <el-step title="待支付" />
          <el-step title="待发货" />
          <el-step title="已发货" />
          <el-step title="已完成" />
        </el-steps>
      </div>

      <!-- 订单基本信息 -->
      <div class="info-section">
        <h3>订单信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(orderInfo.status)">
              {{ orderInfo.statusText }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商家信息">{{ orderInfo.merchantName }}</el-descriptions-item>
          <el-descriptions-item label="用户信息">
            {{ orderInfo.userName }} ({{ orderInfo.userPhone }})
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatDateTime(orderInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ formatDateTime(orderInfo.paymentTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ paymentMethodMap[orderInfo.paymentMethod] }}</el-descriptions-item>
          <el-descriptions-item label="支付单号">{{ orderInfo.paymentNo }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 金额信息 -->
      <div class="info-section">
        <h3>金额信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品总额">¥{{ orderInfo.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="运费">¥{{ orderInfo.freightAmount }}</el-descriptions-item>
          <el-descriptions-item label="优惠金额">¥{{ orderInfo.discountAmount }}</el-descriptions-item>
          <el-descriptions-item label="优惠券抵扣">¥{{ orderInfo.couponAmount }}</el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <span class="price">¥{{ orderInfo.payAmount }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 收货信息 -->
      <div class="info-section">
        <h3>收货信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="收货人">{{ orderInfo.receiverName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderInfo.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">
            {{ orderInfo.receiverAddress }} {{ orderInfo.receiverDetailAddress }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 商品信息 -->
      <div class="info-section">
        <h3>商品信息</h3>
        <el-table :data="orderInfo.orderItems" border style="width: 100%">
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <el-image
                :src="row.productImg"
                :preview-src-list="[row.productImg]"
                class="product-image"
              />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" min-width="200" />
          <el-table-column label="规格" width="150">
            <template #default="{ row }">
              {{ formatSpecInfo(row.specInfo) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">¥{{ row.price }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ row.totalAmount }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 物流信息 -->
      <div class="info-section" v-if="orderInfo.status >= 2">
        <h3>物流信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="快递公司">{{ orderInfo.deliveryCompany }}</el-descriptions-item>
          <el-descriptions-item label="快递单号">{{ orderInfo.deliveryNo }}</el-descriptions-item>
          <el-descriptions-item label="发货时间">{{ formatDateTime(orderInfo.deliveryTime) }}</el-descriptions-item>
          <el-descriptions-item label="签收时间">{{ formatDateTime(orderInfo.receiveTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 退款信息 -->
      <div class="info-section" v-if="orderInfo.status === 5 || orderInfo.status === 6">
        <h3>退款信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退款金额">¥{{ orderInfo.refundAmount }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ orderInfo.refundApplyTime }}</el-descriptions-item>
          <el-descriptions-item label="退款原因">{{ orderInfo.refundReason }}</el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag :type="orderInfo.status === 6 ? 'success' : 'warning'">
              {{ orderInfo.status === 6 ? '已退款' : '退款中' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button
          v-if="orderInfo.canCancel"
          type="danger"
          @click="handleForceCancel"
        >
          强制取消
        </el-button>
        <el-button
          v-if="orderInfo.canRefund"
          type="warning"
          @click="handleForceRefund"
        >
          强制退款
        </el-button>
      </div>
    </el-card>

    <!-- 强制取消对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="强制取消订单"
      width="500px"
    >
      <el-form
        ref="cancelFormRef"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="100px"
      >
        <el-form-item label="取消原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancel" :loading="cancelSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 强制退款对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="强制退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <span>¥{{ orderInfo.payAmount }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input
            v-model="refundForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAdminOrderDetail, forceCancel, forceRefund } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 支付方式映射
const paymentMethodMap = {
  'alipay': '支付宝',
  'wechat': '微信支付',
  'balance': '余额支付'
}

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  const statusTypeMap = {
    0: 'info',    // 待支付
    1: 'warning', // 待发货
    2: 'primary', // 已发货
    3: 'success', // 已完成
    4: 'danger',  // 已取消
    5: 'warning', // 退款中
    6: 'info'     // 已退款
  }
  return statusTypeMap[status] || 'info'
}

// 获取订单进度步骤
const getStatusStep = (status) => {
  const stepMap = {
    0: 0, // 待支付
    1: 1, // 待发货
    2: 2, // 已发货
    3: 3, // 已完成
    4: 0, // 已取消
    5: 1, // 退款中
    6: 1  // 已退款
  }
  return stepMap[status] || 0
}

// 数据相关
const loading = ref(false)
const orderInfo = ref({
  orderItems: []
})

// 获取订单详情
const getOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    return
  }

  try {
    loading.value = true
    const response = await getAdminOrderDetail(orderId)
    if (response.code === 200) {
      orderInfo.value = response.data
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateArray) => {
  if (!dateArray) return '--'
  if (Array.isArray(dateArray)) {
    const [year, month, day, hour, minute, second] = dateArray
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
  }
  return dateArray
}

// 格式化规格信息
const formatSpecInfo = (specInfo) => {
  if (!specInfo) return '--'
  try {
    const spec = JSON.parse(specInfo)
    return Object.entries(spec)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ')
  } catch (error) {
    return specInfo
  }
}

// 返回列表页
const goBack = () => {
  router.push('/admin/order/list')
}

// 强制取消相关
const cancelDialogVisible = ref(false)
const cancelSubmitting = ref(false)
const cancelForm = reactive({
  reason: ''
})

const cancelRules = {
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' }
  ]
}

const handleForceCancel = () => {
  cancelDialogVisible.value = true
  cancelForm.reason = ''
}

const confirmCancel = async () => {
  try {
    cancelSubmitting.value = true
    const response = await forceCancel(orderInfo.value.id, cancelForm.reason)
    if (response.code === 200) {
      ElMessage.success('取消成功')
      cancelDialogVisible.value = false
      getOrderDetail()
    }
  } catch (error) {
    console.error('取消失败:', error)
    ElMessage.error('取消失败')
  } finally {
    cancelSubmitting.value = false
  }
}

// 强制退款相关
const refundDialogVisible = ref(false)
const refundSubmitting = ref(false)
const refundForm = reactive({
  reason: ''
})

const refundRules = {
  reason: [
    { required: true, message: '请输入退款原因', trigger: 'blur' }
  ]
}

const handleForceRefund = () => {
  refundDialogVisible.value = true
  refundForm.reason = ''
}

const confirmRefund = async () => {
  try {
    refundSubmitting.value = true
    const response = await forceRefund(orderInfo.value.id, refundForm.reason)
    if (response.code === 200) {
      ElMessage.success('退款成功')
      refundDialogVisible.value = false
      getOrderDetail()
    }
  } catch (error) {
    console.error('退款失败:', error)
    ElMessage.error('退款失败')
  } finally {
    refundSubmitting.value = false
  }
}

// 初始化
onMounted(() => {
  getOrderDetail()
})
</script>

<style scoped>
.order-detail {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.status-bar {
  padding: 20px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.info-section {
  margin-bottom: 30px;
}

.info-section h3 {
  margin-bottom: 20px;
  font-weight: 500;
  color: #303133;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.action-bar {
  margin-top: 30px;
  text-align: center;
}

.price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}
</style> 